package vip.liux.front.adapter.controller;

import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.annotation.CurrentSecurityContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import vip.liux.core.utils.JsonUtils;
import vip.liux.front.infrastructure.utils.SseEmitterManager;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/api/sse")
public class SseController {

    /**
     * sse 订阅消息
     */
    @GetMapping(path = "/subscribe", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    @ResponseBody
    public SseEmitter subscribe(@CurrentSecurityContext(expression = "authentication.name") String username) {
        // 用户上线了，直接推送积压消息
        // threadPoolTaskExecutor.execute(() -> sysMessageUserService.sendOnlineMessage(id));
        SseEmitter sseEmitter = SseEmitterManager.connect(username);
        SseEmitterManager.sendMessage(username, JsonUtils.toJson(Map.of("message", "Welcome!")));

        return sseEmitter;
    }

    /**
     * sse 订阅消息
     */
    @Async
    @GetMapping(path = "/unsubscribe")
    @ResponseBody
    public CompletableFuture<Void> unsubscribe(@CurrentSecurityContext(expression = "authentication.name") String username) {
        SseEmitterManager.removeUser(username);
        return CompletableFuture.completedFuture(null);
    }

    /**
     * sse 发布消息
     */
    @GetMapping(path = "/publish")
    @ResponseBody
    public void publish(String id, String content) {
        SseEmitterManager.sendMessage(id, content);
    }
}
